package org.common.utils.net.netty.bytes;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import org.common.utils.net.netty.bytes.entity.DefaultByteMessage;
import org.common.utils.net.netty.core.NettyDecode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;

/**
 * 默认的Byte解码器 , 数据格式为：| 类型(1) | 序列号(8) | 消息号(8) | 数据长度(4) | 数据 |
 * @author zhouzhibing
 * @date 2025/11/13 15:28
 */
@ChannelHandler.Sharable
public class DefaultByteDecode extends NettyDecode  {

    private static final Logger log = LoggerFactory.getLogger(DefaultByteDecode.class);

    @Override
    protected void decode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
        ByteBuf in = (ByteBuf) msg;
        if(in.readableBytes() < Const.HEADER_LENGTH) {
            return;
        }

        try {
            in.markReaderIndex();
            byte type = in.readByte();
            long serialNo = in.readLong();
            long messageId = in.readLong();
            int dataLength = in.readInt();

            //数据体长度不对
            int readableBytes = in.readableBytes();
            if(readableBytes < dataLength) {
                in.resetReaderIndex();
                log.warn("receive byte dataLength error , messageId = {} , dataLength = {} , readableBytes = {}" , messageId , dataLength , readableBytes);
                return ;
            }

            byte[] data = new byte[dataLength];
            in.readBytes(data);

            out.add(new DefaultByteMessage(type , serialNo, messageId, data));
//            System.out.println("NettyServer: receive message success , message = " + msg);
        } catch (Exception e) {
            in.resetReaderIndex();
            log.error("decode error", e);
        }
    }
}
